package com.jt;

import jdk.internal.org.objectweb.asm.Handle;
import sun.dc.pr.PRError;

import java.lang.ref.PhantomReference;
import java.util.Iterator;

public class MyStatck<T>  implements Iterable<T>{


    private  Node<T>  head;

    private  int  size;

    //初始化栈


    public MyStatck() {
        head=null;
        size=0;
    }

    //获取栈的大小
    public  int  size(){
        return  size;
    }

    //判断栈是否为空
    public  boolean  isEmpty(){
        return   size==0;
    }

    //向栈中放入元素
    public  void  push(T t){
        Node<T> tNode = new Node<>(t, null);
        if(head==null){
            head=tNode;
        }else {
            Node oldNode=head;
            head=tNode;
            head.next=oldNode;
        }
        size++;
    }

    //从栈中取出元素
    public  T  pop(){
        Node<T> curNode=head;
        if(head==null){
            return null;
        }else{
            head=head.next;
        }
        size--;
        return curNode.item;
    }


   @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }

    private  class Node<T>{
          T  item;

          Node  next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }


    class  MyIterator  implements Iterator<T>{
        private  Node<T> node;

        public MyIterator() {
            this.node = head;
        }

        @Override
        public boolean hasNext() {
            if(node!=null){
                return true;
            }
            return false;
        }

        @Override
        public T next() {
            T item = node.item;
            node=node.next;
            return item;
        }


    }

}
